package cn.edu.hust.cm.lib.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import cn.edu.hust.cm.lib.IOUtils;
import cn.edu.hust.cm.lib.JavaLog;

/**
 * 通过jdbc操作数据库的工具类
 * 
 * @author Administrator
 * 
 */
public class DbUtil {
	private static final Properties DB_CONFIG;
	private static final String KEY_DB_DRIVER = "database.driver";
	private static final String KEY_DB_URL = "database.url";
	private static final String KEY_DB_USER = "database.user";
	private static final String KEY_DB_PASSWORD = "database.password";
	private static final String KEY_DB_POOL_SIZE_MAX = "database.pool.size.max";
	private static final String KEY_DB_POOL_SIZE_INTITIAL = "database.pool.size.initial";

	/*
	 * 缺省使用数据库连接池
	 */
	private static boolean useDbPool = true;

	static {
		DB_CONFIG = IOUtils.getProperties(null, "db_mysql.properties");

		useDbPool = useDbPool();

		// 加载jdbc驱动
		try {
			Class.forName(getDriver());
		} catch (ClassNotFoundException e) {
			JavaLog.e(e.getMessage());
		}
	}

	// TODO 用自己的数据库连接池改进性能
	private static Connection getConnectionFromPool() {
		Connection conn = null;
		if (useDbPool) {
			DbConnPool pool = DbConnPool.getInstance();
			conn = pool.get();
		} else {
			conn = getConnectionFromDriver();
		}
		return conn;
	}

	// XXX 异常处理是否得当
	static ConnectionWrapper getConnectionFromDriver() {
		try {
			Connection conn = DriverManager.getConnection(getUrl(), getUser(),
					getPassword());
			return null == conn ? null : new ConnectionWrapper(conn);
		} catch (SQLException e) {
			JavaLog.e(e.getMessage());
		}
		return null;
	}

	/**
	 * 获取jdbc数据库连接
	 * 
	 * @return jdbc数据库连接
	 */
	public static Connection getConn() {
		return getConnectionFromPool();
	}

	private static String getDriver() {
		return DB_CONFIG.getProperty(KEY_DB_DRIVER);
	}

	private static String getUrl() {
		return DB_CONFIG.getProperty(KEY_DB_URL);
	}

	private static String getUser() {
		return DB_CONFIG.getProperty(KEY_DB_USER);
	}

	private static String getPassword() {
		return DB_CONFIG.getProperty(KEY_DB_PASSWORD);
	}

	public static int getPoolSizeMax() {
		String poolSize = DB_CONFIG.getProperty(KEY_DB_POOL_SIZE_MAX);
		return null == poolSize ? 0 : Integer.parseInt(poolSize);
	}

	public static int getPoolSizeInitial() {
		String poolSize = DB_CONFIG.getProperty(KEY_DB_POOL_SIZE_INTITIAL);
		return null == poolSize ? 0 : Integer.parseInt(poolSize);
	}

	public static boolean useDbPool() {
		return 0 != getPoolSizeInitial();
	}
}
